package com.leinao.team.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.leinao.commons.Response;
import com.leinao.commons.ResponseMessage;
import com.leinao.config.EnvironmentConfig;
import com.leinao.config.RedisCacheConfig;
import com.leinao.constant.Constant;
import com.leinao.constant.LoginEnum;
import com.leinao.constant.ParameterEnum;
import com.leinao.constant.TeamErrorEnum;
import com.leinao.login.dto.LoginResultDto;
import com.leinao.team.dao.TeamMapper;
import com.leinao.team.dto.*;
import com.leinao.team.model.PaiTeamInfo;
import com.leinao.team.model.PaiTeamMember;
import com.leinao.team.model.UserInfo;
import com.leinao.team.service.TeamService;
import com.leinao.util.page.PageInfo;
import com.leinao.util.sha.RSAUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 * @Description 团队服务
 * @author weiwei
 * @date 2019/4/23 13:28
 * @Version 1.0
 */
@Service
public class TeamServiceImpl implements TeamService {

    private static Logger logger = LoggerFactory.getLogger(TeamServiceImpl.class);

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    EnvironmentConfig env;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    RedisCacheConfig redisCacheConfig;

    /**
     * 功能描述: 获取团队列表
     * @param: userId 用户ID
     * @param: role 1为自己创建 0为加入团队
     * @return: List<TeamListDto> 团队list
     * @auther: huopengfei
     * @date: 2019/4/23 17:13
     */
    @Override
    public Response<TeamBeanDto> getTeamList(String userId, Integer role) {
        Response<TeamBeanDto> response = new Response<>();
        List<TeamListDto> teamList = teamMapper.getTeamList(userId, role);
        String createTeamOrNot = teamMapper.getCreateTeamOrNot(userId);
        boolean flag=false;
        if(null!=createTeamOrNot){
            flag=true;
        }
        TeamBeanDto teamBeanDto = new TeamBeanDto();
        teamBeanDto.setCreateTeam(flag);
        teamBeanDto.setTeamList(teamList);
        response.setData(teamBeanDto);
        response.setMessage(ResponseMessage.ok());
        return response;
    }
    /**
     * 功能描述: 获取团队列表带算力
     * @param: userId 用户ID
     * @param: role 1为自己创建 0为加入团队
     * @return: List<TeamListDto> 团队list
     * @auther: huopengfei
     * @date: 2019/4/23 17:13
     */
    @Override
    public Response<List<TeamListDto>> getTeamListWithPower(String userId) {
        Response<List<TeamListDto>> response = new Response<>();
        List<TeamListDto> teamList = teamMapper.getTeamListWithPower(userId);
        if( null != teamList && teamList.size() > 0){
            Jedis jedis = null;
            try {
                JedisPool jedisPool = redisCacheConfig.getJedisPool();
                jedis = jedisPool.getResource();
                // 扣除redis中的
                for (TeamListDto team : teamList) {
                    BigDecimal surplus = team.getPower();
                    // 获取团队创建者id
                    String adminId = team.getAdminId();
                    // 取出redis中的值
                    List<String> jobs = jedis.hvals(Constant.USER_RUNNING_JOB + adminId);
                    // 如果数值不为空，进行扣减
                    if( null != jobs && jobs.size() > 0){
                        BigDecimal deductionValue = BigDecimal.ZERO;
                        for(String str : jobs) {
                            deductionValue = deductionValue.add(new BigDecimal(str));
                        }
                        surplus = surplus.subtract(deductionValue);
                        team.setPower(surplus);
                    }
                }
            }catch (Exception e){
                logger.error("获取团队算力列表报错，case：" + e.getMessage());
                e.printStackTrace();
            }finally {
                if(null != jedis){
                    jedis.close();
                }
            }
        }
        response.setData(teamList);
        response.setMessage(ResponseMessage.ok());
        return response;
    }

    /**
     * @Description 获取团队近期算力使用情况
     * @param teamId 团队Id
     * @param daysCount    获取最近多少天的使用情况
     * @return 团队近期算力使用情况
     * @author:    weiwei
     * @Date:  2019/4/23 16:56
     */
    @Override
    public Response<List<TeamCalculationRecentUsageDto>> getTeamCalculationRecentUsage(Long teamId,
                                                                Integer daysCount, LoginResultDto userInfo) {

        String teamMemberOrNot = teamMapper.getTeamMemberOrNot(teamId, userInfo.getUserId());
        if(null == teamMemberOrNot){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.NOT_A_MEMBER.getSeq(),TeamErrorEnum.NOT_A_MEMBER.getDesc(),
                    null);
        }

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, - (daysCount - 1));
        Date time=cal.getTime();
        String endDay = new SimpleDateFormat("yyyy-MM-dd").format(time);
        List<TeamCalculationRecentUsageDto> teamCalculationRecentUsage = teamMapper.getTeamCalculationRecentUsage(teamId, endDay);

        //得到最近日期集合
        List<String> dateList = new ArrayList<>();
        for (int i = 0; i < daysCount; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, - (daysCount - i - 1));
            Date date = calendar.getTime();
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
            dateList.add(dateStr);
        }
        List<TeamCalculationRecentUsageDto> teamCalculationRecentUsageList = new ArrayList<>();

        //判定查询结果与日期结果
        for (int i = 0; i < dateList.size(); i++) {
            boolean flag = false;
            for (int j = 0; j < teamCalculationRecentUsage.size(); j++) {
                //如果该日期存在使用
                if(dateList.get(i).equals(teamCalculationRecentUsage.get(j).getUseData())){
                    flag = true;
                    teamCalculationRecentUsageList.add(new TeamCalculationRecentUsageDto(teamCalculationRecentUsage.get(j).getUserdCalculation(), teamCalculationRecentUsage.get(j).getUseData()));
                }
            }
            if(!flag) {
                //如果日期没有使用
                teamCalculationRecentUsageList.add(new TeamCalculationRecentUsageDto(new BigDecimal(0), dateList.get(i)));
            }
        }
        return Response.ok(teamCalculationRecentUsageList);
    }

 /**
     *
     * @Description:  创建团队
     * @param name : 团队名称
     * @param introduction : 团队简介
     * @param userId : 用户ID
     * @param emails : 邀请团队成员邮箱，多个以逗号隔开
     * @return: com.leinao.commons.Response<java.lang.Object>
     * @Author: 曹阳
     * @date: 2019/4/23 17:42
     *
     **/
    @Override
    public Response<PaiTeamInfo> creatPaiTeam(String name, String introduction, String userId, String emails) {
        PaiTeamInfo paiTeamInfo = teamMapper.getPaiTeamByAdminId(userId);
        if(null == paiTeamInfo) {
            paiTeamInfo = new PaiTeamInfo();
            paiTeamInfo.setAdminId(userId);
            paiTeamInfo.setName(name);
            paiTeamInfo.setIntroduction(introduction);
            int result = teamMapper.createPaiTeam(paiTeamInfo);
            if (result == 1) {
                PaiTeamMember paiTeamMember = new PaiTeamMember();
                paiTeamMember.setRole(1);
                paiTeamMember.setTeamId(paiTeamInfo.getId());
                paiTeamMember.setUserId(userId);
                paiTeamMember.setSource(0);
                paiTeamMember.setPowerStatus(0);
                teamMapper.addTeamAdmin(paiTeamMember);
                if(StringUtils.isNotBlank(emails)) {
                    sendTeamMemberEmail(emails, paiTeamInfo.getId(), userId);
                }
                return Response.ok(paiTeamInfo);
            } else {
                return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_NAMEEXIST.getSeq(), TeamErrorEnum.TEAM_NAMEEXIST.getDesc(), null);
            }
        }else{
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_ADMINLIMIT.getSeq(), TeamErrorEnum.TEAM_ADMINLIMIT.getDesc(), null);
        }
    }

    /**
     *
     * @Description:  添加团队成员
     * @param userId : 成员ID
     * @param teamId : 团队ID
     * @param data : 邀请链接数据
     * @return: com.leinao.commons.Response<java.lang.Object>
     * @Author: 曹阳
     * @date: 2019/4/24 9:32
     *
     **/
    @Override
    public Response<Void> addTeamMember(String userId, Long teamId, String data) {
        Jedis jedis = null;
        try {
            JedisPool jedisPool = redisCacheConfig.getJedisPool();
            jedis = jedisPool.getResource();
            if(jedis.exists(data)) {
                Long time = System.currentTimeMillis() - Long.valueOf(jedis.get(data));
                if (time < 1000 * 60 * 24 * 7) {
                    jedis.del(data);
                    PaiTeamInfo paiTeamInfo = teamMapper.getTeamDetail(teamId);
                    if (paiTeamInfo == null) {
                        return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_IS_NOT_CREATED.getSeq(), TeamErrorEnum.TEAM_IS_NOT_CREATED.getDesc(), null);
                    }
                    UserInfo userInfo = teamMapper.getUserInfoByEmailOrUserId(userId);
                    if (userInfo == null) {
                        return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.USER_NOT_EXIST.getSeq(), LoginEnum.USER_NOT_EXIST.getDesc(), null);
                    }
                    Integer count = teamMapper.getTeamCountByUserId(userId);
                    if (count < 5) {
                        Integer result = teamMapper.updateTeamMemberDel(teamId, userId);
                        if (result == 1) {
                            return Response.ok();
                        }
                        PaiTeamMember paiTeamMember = new PaiTeamMember();
                        paiTeamMember.setRole(0);
                        paiTeamMember.setTeamId(teamId);
                        paiTeamMember.setUserId(userId);
                        paiTeamMember.setSource(1);
                        paiTeamMember.setPowerStatus(0);
                        result = teamMapper.addTeamMember(paiTeamMember);
                        if (result == 1) {
                            return Response.ok();
                        } else {
                            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_MEMBEREXIST.getSeq(), TeamErrorEnum.TEAM_MEMBEREXIST.getDesc(), null);
                        }
                    } else {
                        return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_MEMBERLIMIT.getSeq(), TeamErrorEnum.TEAM_MEMBERLIMIT.getDesc(), null);
                    }

                }
            }
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMURL_EXPIRED.getSeq(), TeamErrorEnum.TEAMURL_EXPIRED.getDesc(), null);
        }catch (Exception e){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMURL_PARAMETER_ERROR.getSeq(), TeamErrorEnum.TEAMURL_PARAMETER_ERROR.getDesc(), null);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }


    }

    /**
     *
     * @Description: 验证邀请链接
     * @param data : 邀请链接数据
     * @return: com.leinao.commons.Response<com.leinao.team.dto.TeamMemberInviteDataDto>
     * @Author: 曹阳
     * @date: 2019/4/29 16:09
     *
     **/
    @Override
    public Response<TeamMemberInviteDataDto> checkUrlData(String data) {
        Jedis jedis = null;
        try {
            JedisPool jedisPool = redisCacheConfig.getJedisPool();
            jedis = jedisPool.getResource();
            if(jedis.exists(data)) {
                Long time = System.currentTimeMillis() - Long.valueOf(jedis.get(data));
                if (time < 1000 * 60 * 24 * 7) {
                    data = RSAUtil.decPassWord(data);
                    String datas[] = data.split("@@");
                    if (datas.length != 2) {
                        return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMURL_EXPIRED.getSeq(), TeamErrorEnum.TEAMURL_EXPIRED.getDesc(), null);
                    }
                    TeamMemberInviteDataDto inviteData = new TeamMemberInviteDataDto();
                    String memberId = datas[1];
                    Long teamId = Long.parseLong(datas[0]);
                    PaiTeamInfo paiTeamInfo = teamMapper.getTeamDetail(teamId);
                    if (paiTeamInfo == null) {
                        return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMURL_EXPIRED.getSeq(), TeamErrorEnum.TEAMURL_EXPIRED.getDesc(), null);
                    }
                    String adminId = paiTeamInfo.getAdminId();
                    UserInfo userInfo = teamMapper.getUserInfoByEmailOrUserId(adminId);
                    if (userInfo == null) {
                        return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMURL_EXPIRED.getSeq(), TeamErrorEnum.TEAMURL_EXPIRED.getDesc(), null);
                    }
                    inviteData.setTeamName(paiTeamInfo.getName());
                    inviteData.setTeamId(paiTeamInfo.getId());
                    inviteData.setMemberId(memberId);
                    inviteData.setAdminName(userInfo.getUsername());
                    inviteData.setAdminId(userInfo.getId());
                    return Response.ok(inviteData);
                }
            }
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMURL_EXPIRED.getSeq(), TeamErrorEnum.TEAMURL_EXPIRED.getDesc(), null);
        } catch (Exception e) {
            logger.error("get redisResource failed");
            logger.error(e.getMessage(), e);
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAMURL_EXPIRED.getSeq(), TeamErrorEnum.TEAMURL_EXPIRED.getDesc(), null);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     * 功能描述: 获取团队详情
     * @param: id 团队ID
     * @return:
     * @auther: huopengfei
     * @date: 2019/4/24 14:16
     */
    @Override
    public Response<PaiTeamInfo> getTeamDetail(Long id,String userId) {
        String teamMemberOrNot = teamMapper.getTeamMemberOrNot(id, userId);
        if(null == teamMemberOrNot){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.NOT_A_MEMBER.getSeq(),TeamErrorEnum.NOT_A_MEMBER.getDesc(),
                    null);
        }else {
            PaiTeamInfo teamDetail = teamMapper.getTeamDetail(id);
            return Response.ok(teamDetail);
        }
    }



  /**
    * 功能描述：创建团队通知
    * @param leaderId
    * @param teamId
    * @param notice
    * @Return:com.leinao.commons.Response<java.lang.Integer>
    * @Author:cuijianxin
    * @Date:2019/4/26 19:15
    */
    @Override
    public Response<Integer> updateNotice(String leaderId,Long teamId, String notice){
        String userIsLeader = teamMapper.getUserIsLeader(leaderId, teamId);
        if(null==userIsLeader){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.IS_NOT_LEADER.getSeq(),TeamErrorEnum.IS_NOT_LEADER.getDesc(),null);
        }
        if(notice.length()>Constant.TEAM_NOTICE_LENGTH){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.TAC_AFHLAHFJASL.getSeq(),TeamErrorEnum.TAC_AFHLAHFJASL.getDesc(),
                    null);
        }
        int i = teamMapper.updateNotice(teamId,notice);
        return Response.ok(i);

    }

   /**
     * 功能描述：用户使用算例使用状态
     * @param leaderId
     * @param teamId
     * @param userId
     * @param powerStatus
     * @Return:com.leinao.commons.Response<java.lang.Integer>
     * @Author:cuijianxin
     * @Date:2019/4/26 19:15
     */
    @Override
    public Response<Integer> updatePowerstatus(String leaderId,Long teamId,String userId,String powerStatus){
        String userIsLeader = teamMapper.getUserIsLeader(leaderId, teamId);
        if(null==userIsLeader){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.IS_NOT_LEADER.getSeq(),TeamErrorEnum.IS_NOT_LEADER.getDesc(),null);
        }
            int i =teamMapper.updatePowerstatus(teamId,userId,powerStatus);
        return Response.ok(i);

    }


    /**
     *
     * @Description:  验证用户邮箱接口
     * @param email : 用户邮箱
     * @param teamId : 团队ID
     * @return: com.leinao.commons.Response<java.lang.Object>
     * @Author: 曹阳
     * @date: 2019/4/24 15:59
     *
     **/
    @Override
    public Response<UserInfo> getUserInfoByEmail(String email, Long teamId) {
        UserInfo result = teamMapper.getUserInfoByEmailOrUserId(email);
        if(result != null){
            String userId = result.getId();
            PaiTeamMember paiTeamMember = teamMapper.getTeamMember(userId, teamId);
            if(paiTeamMember == null){
                return Response.ok(result);
            }else{
                return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_MEMBEREXIST.getSeq(), TeamErrorEnum.TEAM_MEMBEREXIST.getDesc(), result);
            }
        }else{
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.USER_NOT_EXIST.getSeq(), LoginEnum.USER_NOT_EXIST.getDesc(), null);
        }
    }


    /**
      * 功能描述: 获取团队成员详情分页
      * @param teamId 团队ID
      * @param currentPage 页数
      * @param pageSize 每页条数
      * @Return:com.leinao.commons.Response<com.leinao.util.page.PageInfo>
      * @Author:HuoPengfei
      * @Date:2019/4/24 18:43
      */
    @Override
    public Response<PageInfo> getMemberDetail(String userId,Long teamId, int currentPage, int pageSize) {
        String teamMemberOrNot = teamMapper.getTeamMemberOrNot(teamId, userId);
        if(null==teamMemberOrNot){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.NOT_A_MEMBER.getSeq(),TeamErrorEnum.NOT_A_MEMBER.getDesc(),
                    null);
        }else {
            PageHelper.startPage(currentPage, pageSize);
            List<TeamMemberDto> memberDetail = teamMapper.getMemberDetail(teamId, (currentPage-1)*pageSize, pageSize);
            PageInfo<TeamMemberDto> pageInfo = new PageInfo<>(memberDetail==null?Collections.emptyList(): memberDetail);
            return Response.ok(pageInfo);
        }
    }

    /**
      * 功能描述: 删除成员
      * @param leaderId 队长ID
      * @param userId 用户ID
      * @param teamId 团队ID
      * @Return:com.leinao.commons.Response<java.lang.Integer>
      * @Author:HuoPengfei
      * @Date:2019/4/25 14:42
      */
    @Override
    public Response<Integer> deleteMember(String leaderId,String userId, Long teamId) {
        String userIsLeader = teamMapper.getUserIsLeader(leaderId, teamId);
        if(null==userIsLeader){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.IS_NOT_LEADER.getSeq(),TeamErrorEnum.IS_NOT_LEADER.getDesc(),null);
        }
        int i = teamMapper.deleteMember(userId, teamId);
        return Response.ok(i);
    }

    /**
      * 功能描述: 退出团队
      * @param userId
      * @param teamId
      * @Return:com.leinao.commons.Response<java.lang.Integer>
      * @Author:HuoPengfei
      * @Date:2019/4/25 15:11
      */
    @Override
    public Response<Integer> quitTeam(String userId, Long teamId) {
        int i = teamMapper.quitTeam(userId, teamId);
        return Response.ok(i);
    }

    /**
      * 功能描述: 修改团队简介
      * @param adminId 创建人ID
      * @param introduction 团队简介
      * @param teamId 团队ID
      * @Return:com.leinao.commons.Response<java.lang.Integer>
      * @Author:HuoPengfei
      * @Date:2019/4/25 15:40
      */
    @Override
    public Response<Integer> updateTeamIntro(String adminId,String introduction, Long teamId) {
        String userIsLeader = teamMapper.getUserIsLeader(adminId, teamId);
        if(null==userIsLeader){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.IS_NOT_LEADER.getSeq(),TeamErrorEnum.IS_NOT_LEADER.getDesc(),null);
        }
        int i = teamMapper.updateTeamIntro(introduction, teamId);
        return Response.ok(i);
    }

    /**
     * @Description 查询团队用户的算力使用情况
     * @param teamId 团队Id
     * @return  团队用户的算力使用情况
     * @author:    weiwei
     * @Date:  2019/4/25 10:50
     */
    @Override
    public Response<PageInfo> getTeamUserCalculationRecentUsage(Long teamId, Integer pageSize,
                                                                Integer pageNum, LoginResultDto userInfo) {

        String teamMemberOrNot = teamMapper.getTeamMemberOrNot(teamId, userInfo.getUserId());
        if(null==teamMemberOrNot){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.NOT_A_MEMBER.getSeq(),TeamErrorEnum.NOT_A_MEMBER.getDesc(),
                    null);
        }

        PageHelper.startPage(pageNum, pageSize);

        //查询团队用户算力使用情况
        List<TeamUserInfoDto> teamUserCalculationRecentUsage = teamMapper.getTeamUserCalculationRecentUsage(teamId);

        return Response.ok(new PageInfo<>(teamUserCalculationRecentUsage == null ? Collections.emptyList() : teamUserCalculationRecentUsage));
    }

    /**
     * @Description  团队剩余算力和已使用算力
     * @param teamId  团队Id
     * @return
     * @author:    weiwei
     * @Date:  2019/4/25 15:36
     */
    @Override
    public Response<TeamCalculationDto> getTeamCalculation(Long teamId, LoginResultDto userInfo) {

        String teamMemberOrNot = teamMapper.getTeamMemberOrNot(teamId, userInfo.getUserId());
        if(null == teamMemberOrNot){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.NOT_A_MEMBER.getSeq(),TeamErrorEnum.NOT_A_MEMBER.getDesc(),
                    null);
        }
        return Response.ok(teamMapper.getTeamCalculation(teamId));
    }

  /*
     * @Description: 发送邮箱邀请连接
     * @param emails : 发送的邮箱，多个以逗号隔开
     * @param teamId : 团队ID
     * @param userId : 发送者Id
     * @return: com.leinao.commons.Response<com.leinao.util.page.PageInfo>
     * @Author: 曹阳
     * @date: 2019/4/25 15:11
     *
     **/
    @Override
    public Response<Void> sendTeamMemberEmail(String emails, Long teamId, String userId) {
        List<EmailResponseDto> result = new ArrayList<>();
        String email[] = emails.split(",");
        PaiTeamInfo paiTeamInfo = teamMapper.getTeamDetail(teamId);
        if(paiTeamInfo == null){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_IS_NOT_CREATED.getSeq(), TeamErrorEnum.TEAM_IS_NOT_CREATED.getDesc(), null);
        }
        if(!paiTeamInfo.getAdminId().equals(userId)){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.TEAM_IS_NOT_CREATED.getSeq(), TeamErrorEnum.TEAM_IS_NOT_CREATED.getDesc(), null);
        }
        UserInfo userInfo = teamMapper.getUserInfoByEmailOrUserId(userId);
        if(userInfo == null){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.USER_NOT_EXIST.getSeq(), LoginEnum.USER_NOT_EXIST.getDesc(), null);
        }
        List<UserInfo> userInfos = teamMapper.getUserInfoByEmails(email);
        Jedis jedis = null;
        try {
            JedisPool jedisPool = redisCacheConfig.getJedisPool();
            jedis = jedisPool.getResource();
        }catch (Exception e){
            logger.error("get redisResource failed");
            logger.error(e.getMessage(), e);
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.REDIS_CONNECTION_FAILED.getSeq(), TeamErrorEnum.REDIS_CONNECTION_FAILED.getDesc(), null);
        }
        try {
        for (int i = 0; i < userInfos.size(); i++) {
            UserInfo user = userInfos.get(i);
            String data = teamId + "@@" + user.getId();
            data = RSAUtil.encrypt(data);
            jedis.setex(data, 60 * 24 * 7, Long.toString(System.currentTimeMillis()));
            String url = env.getPaiWebUrl() + "jointeam?data=" + data;
            String begin =  "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td><div style=\"margin: 0 auto; padding: 0; width: 600px; height: 400px; background-color: #fff;\"><div style=\"margin: 0; padding: 45px 63px 0 37px;\"><p style=\"margin: 0; margin-bottom: 26px; padding: 0;\"><img src='http://img.cnbita.com/winning_email_v2.png' width=\"130px\" height=\"25px\" border=\"0\" style=\"display:block;outline:none;text-decoration:none,-ms-interpolation-mode:bicubic;border:none;\" alt=\"彼塔社区\" /></p><p style=\"margin: 0; margin-bottom: 15px; padding: 0;font-family: PingFangSC-Regular;font-size: 14px;color: #2D2F3B;letter-spacing: 0;mso-line-height-rule: exactly;line-height: 24px;\">尊敬的BitaHub用户您好：</p><p style=\"margin: 0; margin-bottom: 9px; padding: 0;font-family: PingFangSC-Regular;font-size: 14px;color: #2D2F3B;letter-spacing: 0;mso-line-height-rule: exactly;line-height: 24px;\">用户<span style='color:#2196f3'>"+ userInfo.getUsername() +"</span>正在邀请您加入团队  <span style='color:#2196f3'>"+ paiTeamInfo.getName() +"</span> ，点击下方链接加入该团队：</p>\n";
            String end = "</p><p style=\"margin: 0; padding: 0;font-family: PingFangSC-Regular;font-size: 14px;color: #99A9AA;letter-spacing: 0;mso-line-height-rule: exactly;line-height: 24px;\">如果您未注册无加入团队的需求，那可能是其他用户误输入了您的邮箱地址，请忽略此邮件。</p></div></div></td></tr></table>";
            String content = begin +
                    "<p><a href="+ url +">" + url + "</a></p>\n" +
                    end;
            String title = "团队邀请";
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("email", email[i]);
            map.add("content", content);
            map.add("title", title);
            restTemplate.postForObject(env.getUserCenterServiceUrl() + "usercenter/sendEmail", map, String.class);
        }
        } catch (Exception e) {
            logger.error("get redisResource failed");
            logger.error(e.getMessage(), e);
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS, TeamErrorEnum.CONNECTION_FAILED.getSeq(), TeamErrorEnum.CONNECTION_FAILED.getDesc(), null);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return Response.ok();
    }

    /**
     * 功能描述: 解散团队
     * @param userId
     * @param teamId
     * @Return:com.leinao.commons.Response<java.lang.Integer>
     * @Author:HuoPengfei
     * @Date:2019/4/25 17:45
     */
    @Override
    public Response<Integer> disbandTeam(String userId, Long teamId) {
        String userIsLeader = teamMapper.getUserIsLeader(userId, teamId);
        if(null==userIsLeader){
            return Response.error(Constant.RESPONSE_STATUS_SUCCESS,TeamErrorEnum.IS_NOT_LEADER.getSeq(),TeamErrorEnum.IS_NOT_LEADER.getDesc(),null);
        }
        int i = teamMapper.disbandTeam(userId, teamId);
        int j = teamMapper.disbandMember(teamId);
        return Response.ok(i);
    }
}
